// pages/healthlife/healthdetails/healthdetails.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    news: {},
    isFavorite: false,
    comments: [],
    commentInput: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const id = Number(options.id);
    console.log('详情页接收到的id:', id);
    this.loadNewsDetail(id);
    this.checkFavoriteStatus(id);
    this.loadComments(id); // 加载评论
  },

  // 加载新闻详情
  loadNewsDetail(id) {
    console.log('开始请求新闻详情，id:', id);
    wx.request({
      url: `http://localhost:8080/news/${id}`,
      method: 'GET',
      success: (res) => {
        console.log('新闻详情返回：', res);
        if (res.data && res.data.data) {
          const news = res.data.data;
          // 替换所有\n为真正的换行符
          if (news.content) {
            news.content = news.content.replace(/\\n/g, '\n');
          }
          this.setData({
            news: {
              id: news.id,
              title: news.title,
              content: news.content,
              coverImg: news.coverImg,
              publishTime: news.publishTime,
              view: news.view || 0,
              favorite: news.favorite || 0,
              type: news.type,
              status: news.status,
              author: news.authorNickname || '佚名'
            }
          });
        }
      },
      fail: (error) => {
        console.error('获取新闻详情失败：', error);
        wx.showToast({
          title: '获取新闻详情失败',
          icon: 'none'
        });
      }
    });
  },

  checkFavoriteStatus: function(id) {
    const userId = wx.getStorageSync('userId');
    if (!userId) return;
    wx.request({
      url: `http://localhost:8080/myfavorites/user/${userId}`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          // type=2为健康资讯
          const fav = res.data.data.find(item => item.articleId === id && item.type === 2);
          this.setData({
            isFavorite: !!fav,
            favoriteId: fav ? fav.id : null
          });
        }
      }
    });
  },

  toggleFavorite: function() {
    const { news, isFavorite, favoriteId } = this.data;
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    if (isFavorite) {
      // 已收藏，发起取消收藏请求
      wx.request({
        url: `http://localhost:8080/myfavorites/${favoriteId}`,
        method: 'DELETE',
        success: (res) => {
          if (res.data.code === 0 || res.data.success) {
            this.setData({
              isFavorite: false,
              favoriteId: null
            });
            wx.setStorageSync('refreshFavorite', true);
            wx.showToast({ title: '已取消收藏', icon: 'none' });
            // 重新拉取详情，获取最新收藏数
            this.loadNewsDetail(news.id);
          }
        }
      });
    } else {
      // 未收藏，发起收藏请求
      wx.request({
        url: `http://localhost:8080/myfavorites`,
        method: 'POST',
        header: { 'content-type': 'application/json' },
        data: {
          userId: Number(userId),
          typeId: Number(news.id), // 注意是typeId
          type: 1, // 健康资讯
          status: 1
        },
        success: (res) => {
          if (res.data.code === 0 || res.data.success) {
            this.setData({
              isFavorite: true,
              favoriteId: res.data.data
            });
            wx.setStorageSync('refreshFavorite', true);
            wx.showToast({ title: '收藏成功', icon: 'success' });
            // 重新拉取详情，获取最新收藏数
            this.loadNewsDetail(news.id);
          } else {
            wx.showToast({
              title: res.data.message || '收藏失败',
              icon: 'none'
            });
          }
        }
      });
    }
  },

  // 加载评论列表
  loadComments(articleId) {
    wx.request({
      url: `http://localhost:8080/comments/1/${articleId}`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.data) {
          this.setData({
            comments: res.data.data.map(comment => ({
              id: comment.id,
              avatar: comment.userAvatar || '/images/ceshi4.jpg',
              nickname: comment.userName || '匿名用户',
              content: comment.content,
              createTime: this.formatTime(comment.createTime) // 格式化时间
            }))
          });
        }
      },
      fail: (error) => {
        console.error('获取评论失败：', error);
        wx.showToast({
          title: '获取评论失败',
          icon: 'none'
        });
      }
    });
  },

  // 格式化时间辅助函数
  formatTime(isoString) {
    if (!isoString) return '';
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  onCommentInput(e) {
    this.setData({ commentInput: e.detail.value });
  },

  onSubmitComment() {
    const content = this.data.commentInput.trim();
    if (!content) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const commentData = {
      userId: Number(userId),
      type: 1, // 健康资讯评论
      typeId: this.data.news.id,
      content: content,
      status: 1
    };

    wx.request({
      url: 'http://localhost:8080/comments',
      method: 'POST',
      data: commentData,
      success: (res) => {
        if (res.data && res.data.success) {
          wx.showToast({
            title: '评论成功',
            icon: 'success'
          });
          this.setData({ commentInput: '' });
          // 重新加载评论列表
          this.loadComments(this.data.news.id);
        } else {
          wx.showToast({
            title: res.data.message || '评论失败',
            icon: 'none'
        });
        }
      },
      fail: (error) => {
        console.error('提交评论失败：', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
})